package com.ywdnf.gomoku.scheduled;

import com.ywdnf.gomoku.model.chess.Game;
import com.ywdnf.gomoku.web.control.GomokuController;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 定时任务
 *
 * @author lss
 * @date 2019-04-16, Tue
 */
@Component
public class ScheduledTask {


  private static final long TIME_HOLD = 1000 * 1800;

  @Scheduled(fixedDelay = 1000 * 3600, initialDelay = 1000)
  private void clearCache() {
    ConcurrentHashMap<String, Game> gs = GomokuController.getAll();
    long cts = System.currentTimeMillis();
    if (!gs.isEmpty()) {
      gs.forEach((key, value) -> {
        if (value.getCurrentRound() == null) {
          // 游戏为开局超时
          if ((value.getLastModified() + TIME_HOLD) < cts) {
            gs.remove(key);
          }
        } else {
          if ((value.getCurrentRound().getCurLayout().getLastModified() + TIME_HOLD) < cts) {
            // 已经结束超时
            gs.remove(key);
          }
        }
      });
    }
  }
}
